package com.gitee.zhziyun.cnfsystem.ui;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.gitee.zhziyun.cnfsystem.config.AvatarConfig;
import com.gitee.zhziyun.cnfsystem.config.IpPortConfig;
import com.gitee.zhziyun.cnfsystem.master.AppMaster;
import com.gitee.zhziyun.cnfsystem.master.AppMasterImpl;
import com.gitee.zhziyun.cnfsystem.model.FileAccept;
import com.gitee.zhziyun.cnfsystem.model.FileSource;
import com.gitee.zhziyun.cnfsystem.ui.component.UserListPane;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Objects;

public class ChatManagerUI extends JFrame {
    private final AppMaster appMaster;
    private ChatUI chatUI;

    public ChatManagerUI(AppMaster appMaster) {
        this.appMaster = appMaster;
        // 创建聊天窗口界面
        this.setTitle("CnfSystem");
        this.setSize(300, 600);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                appMaster.stop();
                dispose();                                 // 关闭窗口
                System.exit(0);                     // 如果需要退出程序
            }
        });

        appMaster.addMulticastListener(new AppMaster.MulticastListener() {
            @Override
            public void onMulticastMessage(String ip, String message) {
                if (chatUI != null) {
                    chatUI.addTextMessage(
                        ip,
                        message,
                        ip.equals(IpPortConfig.getLocalIp())
                    );
                    chatUI.setExtendedState(JFrame.NORMAL);          // 恢复窗口状态
                    chatUI.toFront();                                // 将窗口置于最前
                }
            }

            @Override
            public void onMulticastFileMessage(String ip, FileSource fileSource) {
                if (chatUI != null && !Objects.equals(ip, IpPortConfig.getLocalIp())) {
                    chatUI.setExtendedState(JFrame.NORMAL);          // 恢复窗口状态
                    chatUI.toFront();                                // 将窗口置于最前
                    chatUI.addFileReceiveMessage(ip, fileSource, false);
                }
            }

            @Override
            public void onMulticastFileAccept(String ip, FileAccept fileAccept) {
                if (chatUI != null) {
                    chatUI.getFileSenderMap().get(fileAccept.getUUID()).start(ip, fileAccept.getPort());
                }

            }
        });

        // 创建本机用户信息面板并添加到窗口顶部
        JPanel selfInfoPanel = createSelfInfoPanel();
        UserListPane userListPane = new UserListPane(appMaster);
        
        // 创建底部按钮面板
        JPanel bottomPanel = createBottomPanel();

        this.add(selfInfoPanel, BorderLayout.NORTH);
        this.add(userListPane, BorderLayout.CENTER);
        this.add(bottomPanel, BorderLayout.SOUTH);  // 将按钮面板添加到窗口底部

        // 创建并显示用户列表
        this.setVisible(true);
    }
    
    // 创建本机用户信息面板
    private JPanel createSelfInfoPanel() {
        JPanel selfInfoPanel = new JPanel();
        // 创建主面板（带边框标题）
        selfInfoPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        selfInfoPanel.setBorder(BorderFactory.createTitledBorder("本机用户信息"));
        
        // 添加头像
        JLabel avatarLabel = new JLabel();
        avatarLabel.setIcon(setAvatar(appMaster.getUserInfo().getAvatarId()));
        avatarLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
        selfInfoPanel.add(avatarLabel);
        
        // 创建信息面板（垂直布局）
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        
        // 添加用户信息标签
        infoPanel.add(new JLabel("用户名: " + appMaster.getUserInfo().getUserName()));
        infoPanel.add(new JLabel("主机名: " + appMaster.getUserInfo().getHostName()));

        selfInfoPanel.add(infoPanel);
        return selfInfoPanel;
    }

    //设置头像
    private ImageIcon setAvatar(int avatarId) {
        ImageIcon originalIcon = new ImageIcon(Objects.requireNonNull(
                ChatManagerUI.class.getResource(AvatarConfig.getPathById(avatarId))));
        Image scaledImg = originalIcon.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
        return new ImageIcon(scaledImg);
    }

    /**
     * 创建底部按钮面板（包含加入组播按钮）
     * 注意：这是专门为初学者设计的详细注释版本
     */
    private JPanel createBottomPanel() {
        // 创建底部面板（使用Flow布局使按钮居中）
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); // 添加上下边距
        
        // 创建"加入组播"按钮
        JButton joinMulticastButton = new JButton("加入组播");
        joinMulticastButton.setPreferredSize(new Dimension(120, 30)); // 设置按钮尺寸
        
        // 为按钮添加事件监听器（这里是空实现，需要您填充业务逻辑）
        joinMulticastButton.addActionListener(e -> {
            if (chatUI == null) {
                chatUI = new ChatUI(appMaster, IpPortConfig.getMulticastIp(), IpPortConfig.getMulticastPort(), () -> {
                    chatUI = null;
                    try {
                        appMaster.multicastMessage(appMaster.getUserInfo().getUserName() + "下线了");
                    } catch (JsonProcessingException ex) {
                        throw new RuntimeException(ex);
                    }
                });

                try {
                    appMaster.multicastMessage(appMaster.getUserInfo().getUserName() + "上线了");
                } catch (JsonProcessingException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                chatUI.setExtendedState(JFrame.NORMAL); // 恢复窗口状态
                chatUI.toFront();                      // 将窗口置于最前
            }
        });
        
        panel.add(joinMulticastButton); // 将按钮添加到面板
        return panel;
    }

    public static void main(String[] args) {
        AppMaster appMaster = new AppMasterImpl("zs", 4);
        new ChatManagerUI(appMaster);
    }
}